package com.example.restdemo.web.controller;

import com.example.restdemo.entity.Book;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;

/**
 * 注意 @RestController 不影响ResponseEntity的使用！
 * 不过还是尽量分开吧。
 * <p>
 * Created by 张少昆 on 2017/12/5.
 */
@Controller
@RequestMapping( "/shop" )
public class ShopController {


    /**
     * 保存book
     *
     * @param book
     * @return
     */
    @RequestMapping( value = "/book", method = RequestMethod.POST )
    public ResponseEntity saveBook( Book book){
        System.out.println(LocalDateTime.now() + "-[保存]：book=" + book);
        //此处应该去数据库查询，略。直接返回成功。
        //bookService.save(book);
        return ResponseEntity.ok().build();//保存成功，直接返回200
//        return ResponseEntity.status(400).body("泥垢了！");
    }

    /**
     * 删除book
     *
     * @param id
     * @return
     */
    @RequestMapping( value = "/book/{id}", method = RequestMethod.DELETE )
    public ResponseEntity deleteBook(@PathVariable( "id" ) String id){
        System.out.println(LocalDateTime.now() + "-[删除]：id=" + id);
        //此处应该去数据库查询，略。直接返回成功。
        //bookService.delete(id);
        return ResponseEntity.ok().build();//删除成功，直接返回200
    }

    /**
     * 更新（修改）book
     *
     * @param id
     * @return
     */
    @RequestMapping( value = "/book/{id}", method = RequestMethod.PUT )
    public ResponseEntity updateBook(@PathVariable( "id" ) String id, Book book){
        System.out.println(LocalDateTime.now() + "-[更新]：id=" + id + ", book=" + book);
        //此处应该去数据库查询，略。直接返回成功。
        // book.setId(id);
        // bookService.update(book);
        return ResponseEntity.ok().build();
    }

    /**
     * 查找book
     *
     * @param id
     * @return
     */
    @RequestMapping( value = "/book/{id}", method = RequestMethod.GET )
    @ResponseBody
    public Book getBook(@PathVariable( "id" ) String id){
        System.out.println(LocalDateTime.now() + "-[查找]：id=" + id);
        //此处应该去数据库查询，略。使用new的对象来模拟查询返回的对象。

        Book book = new Book();
        book.setId(id);
        book.setName("Python Cook Book");
        book.setTitle("..");
        book.setAuthor("Sylar");
        book.setPrice(59.99d);

        return book; //或者返回 ResponseEntity.ok(book).build();
    }

}
